package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.TurnoverStatistics;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间区间的营业额
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //查出所有的区间订单
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<Orders> turnoverList = orderMapper.getByTimePeriod(beginTime, endTime, Orders.COMPLETED);

        //用来存储日期对应的营业额
        Map<LocalDate, BigDecimal> map = new HashMap<>();

        //计算出每天的营业额
        for (Orders orders : turnoverList) {
            LocalDate localDate = LocalDate.from(orders.getDeliveryTime());
            map.put(localDate, map.getOrDefault(localDate, BigDecimal.valueOf(0.0)).add(orders.getAmount()));
        }

        //用来拼接字符串
        StringJoiner sj1 = new StringJoiner(",");
        StringJoiner sj2 = new StringJoiner(",");
        sj1.add(begin.toString());
        sj2.add(map.getOrDefault(begin, BigDecimal.valueOf(0.0)).toString());

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            sj1.add(begin.toString());
            sj2.add(map.getOrDefault(begin, BigDecimal.valueOf(0.0)).toString());
        }
        //设置日期
        String dateListStr = sj1.toString();
        String turnListStr = sj2.toString();

        return TurnoverReportVO.builder()
                .dateList(dateListStr)
                .turnoverList(turnListStr)
                .build();
    }

    /**
     * 统计指定时间区间用户数据
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //查出所有的区间订单
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<User> userList = userMapper.getByCreateTime(beginTime, endTime);
        Integer nowNumber = userMapper.getBydateline(beginTime);
        //用来存储日期对应的新增用户数据
        Map<LocalDate, Integer> map = new HashMap<>();

        for (User user : userList) {
            LocalDate localDate = LocalDate.from(user.getCreateTime());
            map.put(localDate, map.getOrDefault(localDate, 0)+1);
        }

        //用来拼接字符串
        StringJoiner date = new StringJoiner(",");
        StringJoiner newUserNumber = new StringJoiner(",");
        StringJoiner userNumber = new StringJoiner(",");
        //添加第一天数据
        date.add(begin.toString());
        newUserNumber.add(map.getOrDefault(begin, 0).toString());
        nowNumber += map.getOrDefault(begin, 0);
        userNumber.add(nowNumber.toString());

        //统计每一天数据
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            date.add(begin.toString());
            newUserNumber.add(map.getOrDefault(begin, 0).toString());
            nowNumber += map.getOrDefault(begin, 0);
            userNumber.add(nowNumber.toString());
        }
        //设置日期
        String dateListStr = date.toString();
        String newUserListStr = newUserNumber.toString();
        String userListStr = userNumber.toString();

        //封装
        return UserReportVO.builder()
                .dateList(dateListStr)
                .newUserList(newUserListStr)
                .totalUserList(userListStr)
                .build();
    }

    /**
     * 统计指定时间区间的订单数据
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //总订单数和有效订单数，订单完成率
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        Double orderCompletionRate = 0.0;

        //开始和结束的时间区间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<Orders> ordersList = orderMapper.getByTimePeriod(beginTime, endTime, null);
        totalOrderCount = ordersList.size();

        //每日订单map
        Map<LocalDate, Integer> map1 = new HashMap<>();
        //每日有效订单map
        Map<LocalDate, Integer> map2 = new HashMap<>();

        for (Orders orders : ordersList) {
            LocalDate localDate = LocalDate.from(orders.getOrderTime());
            map1.put(localDate, map1.getOrDefault(localDate, 0)+1);
            if (orders.getStatus().equals(Orders.COMPLETED)){
                map2.put(localDate, map2.getOrDefault(localDate, 0)+1);
                validOrderCount += 1;
            }
        }

        //计算完成率
        orderCompletionRate =  ((double)validOrderCount / totalOrderCount);

        StringJoiner date = new StringJoiner(",");
        StringJoiner totalOrder = new StringJoiner(",");
        StringJoiner validOrder = new StringJoiner(",");

        //将第一天的数据加入
        date.add(begin.toString());
        totalOrder.add(map1.getOrDefault(begin, 0).toString());
        validOrder.add(map2.getOrDefault(begin, 0).toString());

        //加入每一天的数据
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            date.add(begin.toString());
            totalOrder.add(map1.getOrDefault(begin, 0).toString());
            validOrder.add(map2.getOrDefault(begin, 0).toString());
        }

        return OrderReportVO.builder()
                .dateList(date.toString())
                .orderCountList(totalOrder.toString())
                .validOrderCountList(validOrder.toString())
                .totalOrderCount(totalOrderCount).validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计指定区间销量排名前10的商品
     */
    public SalesTop10ReportVO getSalesTop10Statistics(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop = orderMapper.getSalesTop(beginTime, endTime);

        List<String> names = salesTop.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String namesStr = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numbersStr = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(namesStr)
                .numberList(numbersStr)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库 获取运营数据--查询最近30天的运营数据
        LocalDateTime dateBegin = LocalDateTime.of(LocalDate.now().minusDays(30), LocalTime.MIN);
        LocalDateTime dateEnd = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX);
        BusinessDataVO dataVO = workspaceService.getBusinessData(dateBegin, dateEnd);

        //2.通过POI将数据写入到Excel文件中
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板创建一个新的Excel文件
            assert inputStream != null;
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获取表格文件的Sheet页
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            //填充表头时间
            sheet1.getRow(1).getCell(1).setCellValue("时间："+LocalDate.from(dateBegin)+"至"+LocalDate.from(dateEnd));

            //填充表头数据
            //第四行
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(dataVO.getTurnover());
            row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(dataVO.getNewUsers());

            //第五行
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(dataVO.getValidOrderCount());
            row.getCell(4).setCellValue(dataVO.getUnitPrice());

            //填充明细数据
            int count = 7;
            while (dateBegin.isBefore(dateEnd)){
                //查询某天数据
                BusinessDataVO data = workspaceService.getBusinessData(dateBegin, dateBegin.plusDays(1));

                //获取表单某一行
                row = sheet1.getRow(count);
                row.getCell(1).setCellValue(LocalDate.from(dateBegin).toString());
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());

                dateBegin = dateBegin.plusDays(1);
                count++;
            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭
            outputStream.close();
            excel.close();

        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
}
